package com.restaurant.security.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.restaurant.domain.Employeecredential;
import com.restaurant.service.EmployeecredentialService;

public class CustomeUserDetailsService implements UserDetailsService {

	@Autowired
	private EmployeecredentialService objEmployeecredentialService;
	
	@Override
	public UserDetails loadUserByUsername(String userName)	throws UsernameNotFoundException, DataAccessException {
		Employeecredential employeecredential = null;
		try {
			employeecredential  = (Employeecredential) objEmployeecredentialService.findByName(userName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (employeecredential == null)
            throw new UsernameNotFoundException("Username not found: " + userName);
		UserDetails user = new User(
				employeecredential.getUsername(), 
				employeecredential.getPassword(),
				true, true, true, true, getAuthorities(1));
		return user;
	}
	
	/**
	  * Retrieves the correct ROLE type depending on the access level, where access level is an Integer.
	  * Basically, this interprets the access value whether it's for a regular user or admin.
	  *
	  * @param access an integer value representing the access of the user
	  * @return collection of granted authorities
	  */
	  public Collection<GrantedAuthority> getAuthorities(Integer access) {
		   // Create a list of grants for this user
		   List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(2);
		    
		   // All users are granted with ROLE_USER access
		   // Therefore this user gets a ROLE_USER by default
		  authList.add(new GrantedAuthorityImpl("ROLE_USER"));
		    
		   // Check if this user has admin access
		   // We interpret Integer(1) as an admin user
//		   if ( access.compareTo(1) == 0) {
//		    // User has admin access
//		    authList.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
//		   }
		 
		   // Return list of granted authorities
		   return authList;
	   }

}
